'use client';

import { useState, useEffect } from 'react';

interface CarConfig {
  config_id: number;
  name: string;
}

interface ConfigSelectorProps {
  selectedConfigs: number[];
  onConfigChange: (configIds: number[]) => void;
  maxSelections?: number;
}

// 配置分类
const configCategories = {
  exterior: [1, 2, 3, 4, 5], // 外观配置
  lighting: [6, 7, 8, 9, 10, 11, 12, 13, 14], // 灯光配置
  steering: [15, 16, 17, 18, 19, 20], // 方向盘和仪表
  seating: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33], // 座椅配置
  interior: [34, 35, 36, 37, 38, 39, 40] // 内饰配置
};

const categoryLabels = {
  exterior: '外观配置',
  lighting: '灯光配置',
  steering: '方向盘与仪表',
  seating: '座椅配置',
  interior: '内饰配置'
};

export default function ConfigSelector({ 
  selectedConfigs, 
  onConfigChange, 
  maxSelections = 8 
}: ConfigSelectorProps) {
  const [configs, setConfigs] = useState<CarConfig[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [activeCategory, setActiveCategory] = useState<string>('all');

  useEffect(() => {
    // 动态导入配置数据
    import('@/../public/config.js')
      .then((module) => {
        setConfigs(module.default || []);
      })
      .catch((error) => {
        console.error('加载配置数据失败:', error);
      });
  }, []);

  // 过滤配置
  const filteredConfigs = configs.filter(config => {
    const matchesSearch = searchTerm === '' || 
      config.name.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesCategory = activeCategory === 'all' || 
      Object.entries(configCategories).some(([category, ids]) => 
        category === activeCategory && ids.includes(config.config_id)
      );
    
    return matchesSearch && matchesCategory;
  });

  // 按分类分组
  const configsByCategory = {
    all: configs,
    ...Object.fromEntries(
      Object.entries(configCategories).map(([category, ids]) => [
        category,
        configs.filter(config => ids.includes(config.config_id))
      ])
    )
  };

  const handleConfigToggle = (configId: number) => {
    if (selectedConfigs.includes(configId)) {
      // 取消选择
      onConfigChange(selectedConfigs.filter(id => id !== configId));
    } else {
      // 选择（检查数量限制）
      if (selectedConfigs.length < maxSelections) {
        onConfigChange([...selectedConfigs, configId]);
      }
    }
  };

  const handleRemoveConfig = (configId: number) => {
    onConfigChange(selectedConfigs.filter(id => id !== configId));
  };

  const getCategoryConfigs = (category: string) => {
    if (category === 'all') {
      return configs;
    }
    return configsByCategory[category as keyof typeof configsByCategory] || [];
  };

  const selectedConfigNames = selectedConfigs.map(id => 
    configs.find(config => config.config_id === id)?.name || ''
  ).filter(name => name !== '');

  return (
    <div className="config-selector space-y-4">
      {/* 搜索和分类筛选 */}
      <div className="space-y-3">
        {/* 搜索框 */}
        <div className="relative">
          <input
            type="text"
            placeholder="搜索配置..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
          {searchTerm && (
            <button
              onClick={() => setSearchTerm('')}
              className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
            >
              ✕
            </button>
          )}
        </div>

        {/* 分类标签 */}
        <div className="flex flex-wrap gap-2">
          <button
            onClick={() => setActiveCategory('all')}
            className={`px-3 py-1 rounded-full text-sm font-medium transition-colors ${
              activeCategory === 'all'
                ? 'bg-blue-600 text-white'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            全部
          </button>
          {Object.entries(categoryLabels).map(([key, label]) => (
            <button
              key={key}
              onClick={() => setActiveCategory(key)}
              className={`px-3 py-1 rounded-full text-sm font-medium transition-colors ${
                activeCategory === key
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              {label}
            </button>
          ))}
        </div>
      </div>

      {/* 已选配置显示 */}
      {selectedConfigs.length > 0 && (
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <div className="flex items-center justify-between mb-2">
            <span className="font-medium text-blue-900">
              已选配置 ({selectedConfigs.length}/{maxSelections})
            </span>
            {selectedConfigs.length >= maxSelections && (
              <span className="text-sm text-red-600 font-medium">
                已达到最大选择数量
              </span>
            )}
          </div>
          <div className="flex flex-wrap gap-2">
            {selectedConfigNames.map((name, index) => (
              <span
                key={selectedConfigs[index]}
                className="inline-flex items-center gap-1 px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm"
              >
                {name}
                <button
                  onClick={() => handleRemoveConfig(selectedConfigs[index])}
                  className="text-blue-600 hover:text-blue-800 text-xs"
                >
                  ✕
                </button>
              </span>
            ))}
          </div>
        </div>
      )}

      {/* 配置列表 */}
      <div className="border border-gray-200 rounded-lg">
        <div className="max-h-64 overflow-y-auto">
          {filteredConfigs.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              未找到匹配的配置
            </div>
          ) : (
            <div className="divide-y divide-gray-100">
              {filteredConfigs.map(config => {
                const isSelected = selectedConfigs.includes(config.config_id);
                const isDisabled = !isSelected && selectedConfigs.length >= maxSelections;
                
                return (
                  <label
                    key={config.config_id}
                    className={`flex items-center p-3 cursor-pointer transition-colors ${
                      isDisabled 
                        ? 'opacity-50 cursor-not-allowed' 
                        : 'hover:bg-gray-50'
                    }`}
                  >
                    <input
                      type="checkbox"
                      checked={isSelected}
                      onChange={() => handleConfigToggle(config.config_id)}
                      disabled={isDisabled}
                      className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                    />
                    <span className={`ml-3 text-sm ${
                      isSelected ? 'text-blue-600 font-medium' : 'text-gray-700'
                    }`}>
                      {config.name}
                    </span>
                    {isDisabled && !isSelected && (
                      <span className="ml-auto text-xs text-gray-400">
                        已达上限
                      </span>
                    )}
                  </label>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* 选择提示 */}
      <div className="text-xs text-gray-500 text-center">
        最多可选择 {maxSelections} 个配置
      </div>
    </div>
  );
}